package com.bitcola.chainserver.chain.trx.service;

import com.bitcola.chainserver.chain.trx.api.*;

import com.bitcola.chainserver.chain.trx.config.Constant;
import com.bitcola.chainserver.chain.trx.core.Credential;
import com.bitcola.chainserver.chain.trx.core.Trc20;
import com.bitcola.chainserver.chain.trx.core.TronApi;
import com.bitcola.chainserver.chain.trx.core.TronKit;
import com.bitcola.chainserver.entity.ColaChainEthKey;
import com.bitcola.chainserver.mapper.ColaChainEthKeyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddressService {
    @Autowired
    ColaChainEthKeyMapper ethKeyMapper;
    public Map<String,String>newAddress()
    {
        Credential c1 = Credential.create();
        Map<String,String>result=new HashMap<>(5);
        result.put("private",c1.getPrivateKey());
        result.put("public",c1.getPublicKey());
        result.put("address",c1.getAddress().toString());
           ColaChainEthKey ethKey = new ColaChainEthKey();
           ethKey.setAddress(c1.getAddress().toString());
           ethKey.setPrivateKey(c1.getPrivateKey());
           ethKey.setPublicKey(c1.getPublicKey());
           ethKeyMapper.insert(ethKey);
        return result;
    }
    public BigDecimal getBalance(String address,String contractAddress) throws Exception {
        TronKit kit = new TronKit(
                TronApi.mainNet(),
                Credential.fromPrivateKey("8D9142B97B38F992B4ADF9FB3D0DD527B1F47BE113C6D0B5C32A0571EF1E7B5F")
        );

        if(StringUtils.isEmpty(contractAddress)){
           return BigDecimal.valueOf(kit.getTrxBalance(address)).divide(BigDecimal.valueOf(Constant.SUN));
        }
        Trc20 token = kit.trc20(contractAddress);
        var value=token.balanceOf(address);
        var decimal=BigDecimal.valueOf(token.decimals().longValue());
         var result =new BigDecimal(value.toString()).divide(BigDecimal.valueOf(Math.pow(10,decimal.doubleValue())),25,RoundingMode.DOWN
         );
         return result;

    }

    public static void main(String[] args) {
        Credential c1 = Credential.create();
        Map<String,String>result=new HashMap<>(5);
        result.put("private",c1.getPrivateKey());
        result.put("public",c1.getPublicKey());
        result.put("address",c1.getAddress().toString());
    }





}
